package com.mystnihon.tdroid.view;

import java.io.File;
import java.net.URI;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.mystnihon.tdroid.R;
import com.mystnihon.tdroid.manager.file.FileManager;
import com.mystnihon.tdroid.manager.file.FileManager.Filter;
import com.mystnihon.tdroid.manager.file.NotMountedStorageException;

public class FileChooserActivity extends SherlockFragmentActivity implements OnItemClickListener {
    public static final int REQUEST_CHOOSE_FILE = 10;
    public static final String EXTRA_NAME_FILTER = "EXTRA_NAME_FILTER";
    public static final String EXTRA_RESPONSE_URI = "EXTRA_RESPONSE_URI";
    public static final String EXTRA_SEARCH_TYPE = "EXTRA_SEARCH_TYPE";
    private static final String TAG = FileChooserActivity.class.getSimpleName();

    ListView mListView;
    FileManager fileMng;
    ArrayList<File> mFiles;
    FileAdapter mAdapter;
    Filter mFilter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_file);

        mFiles = new ArrayList<File>();

        Intent intent = getIntent();
        if (intent != null) {
            String mNameFilter = intent.getStringExtra(EXTRA_NAME_FILTER);
            if (mNameFilter != null)
                mFilter = new Filter(mNameFilter);
        }
        mListView = (ListView) findViewById(R.id.listview_files);
        mAdapter = new FileAdapter(this);
        mListView.setAdapter(mAdapter);
        mListView.setOnItemClickListener(this);
        try {
            fileMng = new FileManager(this);
            mAdapter.setFiles(getFiles(), new FileParent(fileMng.getExternalStorageDirectory(), ""));

        } catch (NotMountedStorageException e) {
            Log.w(TAG, "Erreur while getting files" + e.getStorageState());

        }

    }

    private ArrayList<File> getFiles() {
        if (mFilter != null) {
            return fileMng.listExternalStorageBaseFile(mFilter);
        } else
            return fileMng.listExternalStorageBaseFile();

    }

    class FileParent extends File {
        /**
		 * 
		 */
        private static final long serialVersionUID = -3866071983969330216L;

        public FileParent(String dirPath, String name) {
            super(dirPath, name);
        }

        public FileParent(File dir, String name) {
            super(dir, name);
        }

        public FileParent(String path) {
            super(path);
        }

        public FileParent(URI uri) {
            super(uri);
        }

        public String getName() {
            return "..";
        }
    }

    class ViewHolder {
        TextView mFileName;
        TextView mFileExtension;
        ImageView mIcon;
    }

    class FileAdapter extends BaseAdapter {
        LayoutInflater inflater;
        ArrayList<File> files;

        public FileAdapter(Context context) {
            files = new ArrayList<File>();
            inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        public void setFiles(ArrayList<File> supFiles, FileParent parentFile) {
            if (supFiles != null) {
                files.clear();
                files.add(parentFile);
                files.addAll(supFiles);
                notifyDataSetChanged();
            }
        }

        @Override
        public int getCount() {
            return files.size();
        }

        @Override
        public File getItem(int position) {
            return files.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = inflater.inflate(R.layout.listitem_file, null);
                holder.mFileName = (TextView) convertView.findViewById(R.id.listitem_filename);
                holder.mFileExtension = (TextView) convertView.findViewById(R.id.listitem_fileextension);
                holder.mIcon = (ImageView) convertView.findViewById(R.id.listitem_icon);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            final File file = getItem(position);
            holder.mFileName.setText(file.getName());
            if (file.isDirectory()) {
                holder.mIcon.setImageResource(R.drawable.collections_collection);
            } else {
                holder.mIcon.setImageResource(R.drawable.collections_view_as_list);
            }
            return convertView;
        }

    }

    @Override
    public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
        final File file = mAdapter.getItem(position);
        if (file.isDirectory()) {
            File parent = null;
            if (file.equals(fileMng.getExternalStorageDirectory())) {
                parent = file;
            } else {
                parent = file.getParentFile();
            }
            if (mFilter != null) {
                mAdapter.setFiles(fileMng.listDirectoryFile(file, mFilter), new FileParent(parent, ""));
            } else {
                mAdapter.setFiles(fileMng.listDirectoryFile(file), new FileParent(parent, ""));
            }
        } else {
            Uri uri = Uri.fromFile(file);

            setResult(Activity.RESULT_OK, new Intent().putExtra(EXTRA_RESPONSE_URI, uri));
            finish();
        }
    }
}
